package com.zlt.service.impl;

import com.alibaba.fastjson.JSON;
import com.zlt.dao.CompanyDao;
import com.zlt.dao.Impl.CompanyDaoImpl;
import com.zlt.dao.Impl.RoleDaoImpl;
import com.zlt.dao.Impl.UserDaoImpl;
import com.zlt.dao.RoleDao;
import com.zlt.dao.UserDao;
import com.zlt.dto.RoleDTO;
import com.zlt.dto.UserDTO;
import com.zlt.entity.Company;
import com.zlt.entity.Role;
import com.zlt.entity.User;
import com.zlt.service.UserService;
import com.zlt.util.*;
import com.zlt.vo.ActiveUser;
import org.apache.commons.beanutils.BeanUtils;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();

    private RoleDao roleDao = new RoleDaoImpl();

    private CompanyDao companyDao = new CompanyDaoImpl();


    public String getUserUid(String username) {
        return userDao.getUserUid(username);
    }


    public UUID getUserUid() {
//        userDao.getUserUid();
        return null;
    }


    @Override
    public boolean reg(UserDTO userDto) {

        User user = new User();

        try {
            BeanUtils.copyProperties(user, userDto);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //手机号唯一
        User phone = selectUserByUsername(user.getUsername());
        System.out.println("reg phone:" + phone);
        if (phone != null) {
            return false;
        }

        //邮箱唯一
        User email = selectUserByEmail(user.getEmail());
        System.out.println("reg email:" + email);
        if (email != null) {
            return false;
        }


        //设置参数
        user.setSalt(StringUtil.randomStr(6));
        user.setRegTime(StringUtil.getCurrentTime());
        user.setState(0);
        user.setUid(StringUtil.uuid());

        //密码加密
        user.setPassword(MD5Util.getMD5(user.getPassword(), user.getSalt(), 10));
        System.out.println("reg:" + user);

        //添加用户成功后  添加用户的角色信息
        int insert = userDao.insert(user);
        if (insert > 0) {
            int i = roleDao.addRole(user.getUid(), userDto.getRoles());
            return i > 0;
        }
        return false;
    }

    @Override
    public User selectUserByEmail(String email) {
        Jedis connection = JedisUtil.getConnection();
        String s = connection.get("user:username:" + email);
        //第一次去redis查 现有的用户
        if (s == null) {
            User user = userDao.selectUserByEmail(email, 0);

            //数据库也没有
            if (user == null) {
                return null;
            }
            s = JSON.toJSONString(user);
        }
        connection.close();
        return JSON.parseObject(s, User.class);
    }

    @Override
    public int updateRecruit(UserDTO userDTO) {
        User user = new User();
        try {
            BeanUtils.copyProperties(user, userDTO);

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
//        System.out.println("6666");
//        System.out.println(user.toString());
//        user.setUid("12312");
//        System.out.println(user);
        return userDao.updateRecruit(user);
    }


    @Override
    public String login(UserDTO userDto) {

        User user = selectUserByUsername(userDto.getUsername());
        System.out.println("login:" + user);

        if (user == null) {
            throw new RuntimeException("账号或密码错误");
        }

        //对密码处理
        String password = MD5Util.getMD5(userDto.getPassword(), user.getSalt(), 10);
        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("账号或密码错误");
        }

        if(user.getState().equals(1)){
            throw new RuntimeException("当前账号已注销");
        }

        //账号密码都对了
        return JWTUtil.sign(user.getUsername(), user.getPassword());
    }

    @Override
    public void login(String token) {
        if (!StringUtil.isNotNull(token)) {
            throw new RuntimeException("token无效");
        }

        String username = JWTUtil.getUsername(token);

        if (!StringUtil.isNotNull(username)) {
            throw new RuntimeException("token无效");
        }

        User user = selectUserByUsername(username);

        if (user == null) {
            throw new RuntimeException("token无效");
        }

        if (!JWTUtil.verify(token, username, user.getPassword())) {
            throw new RuntimeException("token无效");
        }

        //token没问题  user保存下来
        //查询当前用户的权限 角色
        ActiveUser activeUser = new ActiveUser();
        try {
            BeanUtils.copyProperties(activeUser, user);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("activeUser:" + activeUser);


        //查询当前用户的角色
        List<Role> roles = selectRolesByUid(activeUser.getUid());
        System.out.println("roles:" + roles);
        activeUser.setRoles(roles);
        //查询权限
        ActiveUserUtil.set(activeUser);


    }

    @Override
    public List<Role> selectRolesByUid(String uid) {
        Jedis connection = JedisUtil.getConnection();
        List<Role> roles = null;
        //去redis查找
        List<String> lrange = connection.lrange("role:uid:" + uid, 0, -1);
        //第一次数据放入redis
        if (lrange == null || lrange.isEmpty()) {

            roles = userDao.selectRolesByUid(uid);

            //数据库也没有
            if (roles != null && !roles.isEmpty()) {
                // 有数据就放redis
                roles.forEach(r -> {
                    connection.rpush("role:uid:" + uid, JSON.toJSONString(r));
                });
                lrange = connection.lrange("role:uid:" + uid, 0, -1);
            }
        }
        if ((roles == null || roles.isEmpty()) && !lrange.isEmpty()) {
            roles = new ArrayList<>();
            for (String s : lrange) {
                roles.add(JSON.parseObject(s, Role.class));
            }
        }
        connection.close();
        return roles;
    }

    @Override
    public boolean setRole(RoleDTO roleDTO) {
        return false;
    }

    @Override
    public Integer getRoleByUsername(String username) {
        return userDao.getUserRole(username);
    }

    @Override
    public boolean applyToHr(String cname) {
        ActiveUser activeUser = ActiveUserUtil.get();
        if (activeUser == null) {
            throw new RuntimeException("当前未登录，无法申请");
        }

        Company company = companyDao.selectCompanyByCname(cname, 0);
        System.out.println("applyToHr companybYname:" + company);
        //查找申请的公司是否正常存在

        if (company == null) {
            throw new RuntimeException("公司不存在");
        }
        //查找当前用户是否在职
        List<Map<String, Object>> list = userDao.selectUserCompanyByUid(activeUser.getUid());

        if (list == null || list.isEmpty()) {
            //没有在职  在user-company的表中插入当前数据
            return userDao.insertUserCompany(activeUser.getUid(), company.getCid(), 1) > 0;
        } else {
            return userDao.updateUserCompany(activeUser.getUid(), company.getCid(), 1) > 0;
        }

    }

    @Override
    public boolean modify(UserDTO userDto) {

        User user = new User();

        try {
            BeanUtils.copyProperties(user, userDto);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //手机号唯一
        User phone = selectUserByUsername(user.getUsername());
        System.out.println("reg phone:" + phone);
        if (phone == null) {
            return false;
        }

        user.setPassword(MD5Util.getMD5(user.getPassword(), phone.getSalt(), 10));
        System.out.println("reg:" + user);
        int result = userDao.updateUser(user);

        return result > 0;

    }

    @Override
    public boolean modifyByEmail(UserDTO userDto) {
        User user = new User();

        try {
            BeanUtils.copyProperties(user, userDto);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //邮箱唯一
        User email = selectUserByEmail(user.getEmail());
        System.out.println("reg email:" + email);
        if (email == null) {
            return false;
        }



        user.setPassword(MD5Util.getMD5(user.getPassword(), email.getSalt(), 10));
        System.out.println("reg:" + user);


        int result = userDao.updateUserByEmail(user);

        return result > 0;
    }


//    @Override
//    public User loginDo(UserDTO userDto) {
//        User user = userDao.selectUserByUsername(userDto.getUsername());
//        user.setPassword("");
//        return user;
//        return null;
//    }


    @Override
    public User selectUserByUsername(String username) {

        Jedis connection = JedisUtil.getConnection();
        String s = connection.get("user:username:" + username);
        //第一次数据放入redis
        if (s == null) {
            User user = userDao.selectUserByUsername(username, 0);

            //数据库也没有
            if (user == null) {
                return null;
            }
            s = JSON.toJSONString(user);
            connection.set("user:username:" + user.getUsername(), s);

        }
        connection.close();
        return JSON.parseObject(s, User.class);
    }
}

